﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.ObjectModel;
using System.Xml.Linq;

namespace ScrumMonster
{
    public class Sprint
    {
        private List<Task> _tasks;
        private TimeSpan _estimateTime;
        private Project _project;

        public event OnChange OnSprintChange;

        public Project Project
        {
            get
            {
                return _project;
            }
        }

        public ReadOnlyCollection<Task> Tasks
        {
            get
            {                
                return _tasks.AsReadOnly();
            }
        }

        public XElement XElement
        {
            get
            {
                return new XElement("sprint",
                                     new XElement("estimatedtime",
                                         new XElement("days", this._estimateTime.Days),
                                         new XElement("hours", this._estimateTime.Hours),
                                         new XElement("minutes", this._estimateTime.Minutes),
                                         new XElement("tasks", from task in _tasks
                                                           select task.XElement)));                               
            }
        }

        internal Sprint(TimeSpan estimatedTime)
        {
            _tasks = new List<Task>();
        }

        internal Sprint(XElement element)
        {
            this._estimateTime = (from timeSpan in element.Elements("estimatedtime")
                                  select new TimeSpan(int.Parse(timeSpan.Elements("days").First().Value),
                                                      int.Parse(timeSpan.Elements("hours").First().Value),
                                                      int.Parse(timeSpan.Elements("minutes").First().Value), 0) ).First();

            this._tasks = new List<Task>( from task in element.Elements("tasks")
                                          select new Task(task, this));
                                                              
        }

        internal Sprint(List<Task> tasks, TimeSpan estimatedTime)
        {
            _tasks = tasks;
        }

        public void AddTask(Task task)
        {
            _tasks.Add(task);
            _project.Context.WriteToFile(this._project);

            OnSprintChange();
        }

        public void AddTasks(params Task[] tasks)
        {
            foreach (Task task in tasks)
                _tasks.Add(task);

            _project.Context.WriteToFile(this._project);

            OnSprintChange();
        }

        public void ImportTasks(IContext context, params string[] uniqueIdentifiers)
        {

        }

    }
}
